/*
 * vCLURT.cpp
 *
 *  Created on: May 21, 2011
 *      Author: ulas
 */

#include <stdlib.h>
#include "vCLURT.h"
#include "common/PQ.h"
#include "common/sys.h"

vCLURT::vCLURT() {
	DBG("vCL URT init\n");
	PQ = initPQ(URT_PRIORITY_QUEUE_SIZE, vCLURT::getPriority, vCLURT::comparePriority);
	initialize_vCL();
}

STATUS vCLURT::initialize_vCL()
{
	URT_COMMUNICATION_REQUEST_PQ_TYPE* comReqPtr;
	TimeInternal curTime;
	TimeInternal t;
    t.seconds = 0;
    DBG("Initializing vCL for URT\n");
	if ((comReqPtr =  (URT_COMMUNICATION_REQUEST_PQ_TYPE*)malloc(sizeof(URT_COMMUNICATION_REQUEST_PQ_TYPE)))== NULL) {
		DBG("URT.c || cannot allocate memory for comReq\n");
		exit(EXIT_FAILURE);
	}
	getTime(&curTime);
	comReqPtr->ch = 1;
	comReqPtr->nodeId = 1;
	comReqPtr->initialeT = 0;
	comReqPtr->initialdT = 10;
	t.nanoseconds = (comReqPtr->initialeT)*1000000;
	comReqPtr->eT  = addTime( &curTime, &t );
	t.nanoseconds = (comReqPtr->initialdT)*1000000;
	comReqPtr->dT  = addTime( &curTime, &t );

	/*initial configuration*/
    return insertNodeIntoPQ(comReqPtr);
}

STATUS vCLURT::freePQ()
{
	URT_COMMUNICATION_REQUEST_PQ_TYPE* parPtr;
	while( (parPtr = (URT_COMMUNICATION_REQUEST_PQ_TYPE*)popNodeFromPQ()) != NULL) {
		DBG("pq: nodeId:%d, ch:%d, eT:%d.%9d, dT:%d.%9d \n",
													parPtr->nodeId,
													parPtr->ch,
													parPtr->eT.seconds, parPtr->eT.nanoseconds,
													parPtr->dT.seconds, parPtr->dT.nanoseconds);
		free(parPtr);
	}
	freeUpPQ(PQ);
	return OK;
}

STATUS vCLURT::insertNodeIntoPQ(void* node)
{
	return insertNodePQ(PQ, node);
}

U32 vCLURT::getPQSize()
{
	return getSizePQ(PQ);
}

void *vCLURT::peekNodeFromPQ()
{
	return peekPQ(PQ);
}

void *vCLURT::popNodeFromPQ()
{
	return popPQ(PQ);
}

vCLURT::~vCLURT()
{
	NOTIFY("freeing vCL URT\n");
	freePQ();
}
